package com.example.financeapi.config.interceptor;

import com.example.financeapi.config.annotation.AccessLimit;
import com.example.financeapi.utils.HttpUtil;
import com.example.financeapi.utils.JsonUtils;
import com.example.financeapi.utils.RedisUtils;
import com.example.financeapi.entity.vo.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * API请求限流拦截器
 * @author Alvin
 */
@Slf4j
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    /**
     *  预处理回调方法,实现处理器的预处理，第三个参数为响应的处理器,自定义Controller,返回值为true表示继续流程（如调用下一个拦截器或处理器）或者接着执行
     *  postHandle()和afterCompletion()；false表示流程中断，不会继续调用其他的拦截器或处理器，中断执行。
     * @param request   请求
     * @param response  响应
     * @param handler   值
     * @return          布尔类型
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            // Handler 是否为 HandlerMethod 实例
            if(handler instanceof HandlerMethod){
                // 强转
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 获取方法
                Method method = handlerMethod.getMethod();
                // 是否有AccessLimit注解
                if(!method.isAnnotationPresent(AccessLimit.class)){
                    return true;
                }
                // 获取注解内容信息
                AccessLimit accessLimit = method.getAnnotation(AccessLimit.class);
                if(accessLimit == null){
                    return true;
                }
                //请求次数
                int times = accessLimit.times();
                //请求时间范围
                int second = accessLimit.second();
                //根据 IP + API 限流
                String key = HttpUtil.getIpAddr(request) + request.getRequestURI();
                //根据key获取已请求次数
                Integer maxTimes =0;
                String maxTimesStr =redisUtils.get(key);
                maxTimes = StringUtils.isBlank(maxTimesStr)==true?0:Integer.parseInt(maxTimesStr);
                if(maxTimesStr == null){
                    //set时一定要加过期时间
                    redisUtils.set(key, "1", second);
                }else if(maxTimes < times){
                    maxTimes=maxTimes+1;
                    redisUtils.set(key, maxTimes+"", second);
                }else{
                    // 30405 API_REQUEST_TOO_MUCH  请求过于频繁
                    String msg ="请求过于频繁！"+second+"s 中请求了"+maxTimes+"次";
                    out(response, ResultVOUtil.error(msg));
                    return false;
                }
            }
        }catch (Exception e){
            log.error("API请求限流拦截异常,请检查Redis是否开启! msg={},e={}",e.getMessage(),e);
            e.printStackTrace();
        }
        return true;
    }

    /**
     * @Title: out
     * @Description:  response输出JSON数据
     * @param response : 响应请求
     * @param object: object
     * @return void
     **/
    public static void out(ServletResponse response, Object object){
        PrintWriter out = null;
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.println(JsonUtils.toJson(object));
        } catch (Exception e) {
            log.error("输出JSON报错!msg={},e={}",e.getMessage(),e);
            e.printStackTrace();
        }finally{
            if(null != out){
                out.flush();
                out.close();
            }
        }
    }


}
